package rs.etf.es.algorithm.states;

import rs.etf.es.algorithm.Algorithm;
import rs.etf.es.algorithm.AlgorithmState;
import rs.etf.es.algorithm.Constants;
import rs.etf.es.algorithm.Instantiation;
import rs.etf.es.algorithm.JTextAreaLogger;
import rs.etf.es.algorithm.Node;
import rs.etf.es.algorithm.NodeAddressBook;
import rs.etf.es.algorithm.RequestManager;

public class InstantiateNodeState implements AlgorithmState {

    private Algorithm algorithm;
    private Instantiation inst;

    @Override
    public void performAction() {
	JTextAreaLogger.instance().log("");

	RequestManager.instance().takeNextInstatiation();

	JTextAreaLogger.instance().log("Starting update phase for instantiation " + inst.getVariableName() + " - " + inst.getVariableValue() + " = " + inst.getProbability());
	Node instantiatedNode = NodeAddressBook.instance().getNode(inst.getVariableName());

	instantiatedNode.getLambdaValues().put(inst.getVariableValue(), Constants.DEFAULT_LAMBDA_VALUE);
	JTextAreaLogger.instance().log("Setting lambda value in " + instantiatedNode.getName() + " for " + inst.getVariableValue() + " to " + Constants.DEFAULT_LAMBDA_VALUE);
	instantiatedNode.getPiValues().put(inst.getVariableValue(), Constants.DEFAULT_PI_VALUE);
	JTextAreaLogger.instance().log("Setting pi value in " + instantiatedNode.getName() + " for " + inst.getVariableValue() + " to " + Constants.DEFAULT_PI_VALUE);
	instantiatedNode.setProbability(inst.getVariableValue(), Constants.CERTAIN);
	JTextAreaLogger.instance().log("Setting probability of " + inst.getVariableValue() + " in " + instantiatedNode.getName() + " to " + Constants.CERTAIN);

	SetPiAndLambdaValuesToZeroState newState = new SetPiAndLambdaValuesToZeroState();
	newState.setAlgorithm(algorithm);
	newState.setInst(inst);
	algorithm.pushAlgorithmState(newState);
    }

    @Override
    public void setAlgorithm(Algorithm algorithmClass) {
	algorithm = algorithmClass;
    }

    public Instantiation getInst() {
	return inst;
    }

    public void setInst(Instantiation inst) {
	this.inst = inst;
    }

    public AlgorithmState clone() {
	InstantiateNodeState forMemento = new InstantiateNodeState();
	forMemento.setAlgorithm(algorithm);
	forMemento.setInst(new Instantiation(inst.getVariableName(), inst.getVariableValue()));
	return forMemento;
    }

    @Override
    public void refreshNodes() {

    }

}
